package controllers;

import models.TA014;
import models.TB005;
import play.Logger;
import play.mvc.Controller;
import utils.Strings;

import java.util.*;

/**
 * Created by xuyang on 2018/1/11.
 */
public class Bind extends Controller {

    public static void index() {
        template(null, null, null);
    }

    public static void aircraft(String id) {
        TB005 aircraft = TB005.findById(id);

        render(aircraft);
    }

    public static void submitAircraft(String id) {
        params.checkAndParse();

        String text = "";

        if (params.get("remove") != null) {
            Map<String, String[]> selection = params.sub("sel");

            Set templateIds = selection.keySet();

            TB005 aircraft = TB005.findById(id);
            aircraft.removeSlitTemplatesByIds(templateIds);
            aircraft.save();

            flash.success("Successfully remove templates: " + templateIds.toString());

            aircraft(id);
        } else if (params.get("add") != null) {
            templates(id);
        } else if (params.get("addTemplates") != null) {
            Map<String, String[]> selection = params.sub("sel");

            Set templateIds = selection.keySet();

            TB005 aircraft = TB005.findById(id);

            aircraft.addSpliteTemplatesByIds(templateIds);

            aircraft.save();

            flash.success("Successfully add templates: " + templateIds.toString());

            aircraft(id);
        }

    }

    public static void templates(String id) {
        TB005 aircraft = TB005.findById(id);

        String name = params.get("name");
        String smi = params.get("smi");
        String type = params.get("type");

        List<models.TA014> items = null;

        if (!Strings.isNullOrEmpty(name) || !Strings.isNullOrEmpty(smi) || !Strings.isNullOrEmpty(type)) {
            items = TA014.filterBy(name, null, smi, type, -1);
        } else {
            items = new ArrayList<>();
        }

        if (aircraft.split_templates!=null) {
            items.removeAll(aircraft.split_templates);
        }

        render(items, aircraft, name, smi, type);
    }

    public static void template(Long id, String aircrafts, String prefix) {
        TA014 entity = null;
        if (id != null) {
            entity = TA014.findById(id);
        }
        List<TA014> allTemplates = TA014.findAll();
        allTemplates.sort(new Comparator<TA014>() {
            @Override
            public int compare(TA014 o1, TA014 o2) {
                return o1.split_template_name.compareTo(o2.split_template_name);
            }
        });

        prefix = prefix!=null? prefix : "B-";

        render(entity, aircrafts, prefix, allTemplates);
    }


    public static void submitTemplate(Long id, String aircrafts) {
        String[] acs = aircrafts.trim().split("[\\s,;]");
        String prefix = params.get("prefix");
        TA014 entity = TA014.findById(id);

        if (params.get("verify") != null) {

            List<String> notFound = new ArrayList<>();
            for (String ac : acs) {
                if (ac.isEmpty()) {
                    continue;
                }
                if (prefix != null) {
                    ac = prefix + ac;
                }
                TB005 tb005 = TB005.findById(ac);
                if (tb005 == null) {
                    notFound.add(ac);
                }
            }

            if (notFound.isEmpty() ) {
                flash.success("Verified successfully!");
            } else {
                String notFoundMsg = String.join(", ", notFound);
                flash.error("Verified Failed. %s not found.", notFoundMsg);
            }
        } else if (params.get("submit") != null) {
            boolean success = true;
            for (String ac : acs) {
                if (ac.isEmpty()) {
                    continue;
                }
                if (prefix != null) {
                    ac = prefix + ac;
                }
                TB005 tb005 = TB005.findById(ac);
                if (tb005 == null) {
                   flash.error("Fail! %s not found", ac);
                   success = false;
                   break;
                }

                try {
                    tb005.addSpliteTemplatesByIds(Arrays.asList(entity.getId().toString()));
                    tb005.save();
                } catch (Exception e) {
                    Logger.debug("Caught exception when saving !", e);
                    e.printStackTrace();
                    flash.error("Fail! Caught exception when saving !");
                    success = false;
                }
            }

            if (success) {
                flash.success("Successfully bind all aircrafts to template!");
            }
        }

        template(id, aircrafts, prefix);
    }
}
